package com.example.lanouhn.firstapp.activity.activity;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.example.lanouhn.firstapp.R;
import com.example.lanouhn.firstapp.activity.adapter.ClassifyNappyAdapter;
import com.example.lanouhn.firstapp.activity.constants.Constants;
import com.example.lanouhn.firstapp.activity.fragment.ClassifyFragment;
import com.example.lanouhn.firstapp.activity.model.Classify;
import com.example.lanouhn.firstapp.activity.utils.ClassifyJson;
import com.example.lanouhn.firstapp.activity.view.xlistview.XListView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 分类下的二级  目录纸尿裤、奶粉...等等的布局页面
 */
public class NappyActivity extends AppCompatActivity {

    //设置变量
    private XListView listView;
    private ClassifyNappyAdapter adapter;
    //定义数组
    private List<Classify> dataList;

    //
    private int tuyype = 0;
    //加载进度
    private ProgressBar progressBar;

    //返回键
    private ImageView back;
    //搜索键
    private EditText search;
    //下Button标题
    private RadioGroup radioGroup;

    private ClassifyFragment classifyFragment;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_nappy);

        tuyype = getIntent().getIntExtra("type", 0);

        //找控件
        listView = (XListView) findViewById(R.id.nappy_listView);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        back = (ImageView) findViewById(R.id.imageview_left);
        search = (EditText) findViewById(R.id.et_search);
        radioGroup = (RadioGroup) findViewById(R.id.radioGroup);

        //开启加载更多功能 设置上拉加载的开关 false为关闭  不显示
        listView.setPullLoadEnable(false);

        //创建新线程，请求网络数据并解析
        getDateFromWeb();
        //设置item的点击事件
        onItemClickListener();

    }


    private void getDateFromWeb() {


        /**
         * 开启线程
         */
        dataList = new ArrayList<>();
        //加载时显示进度条  优化用户体验
        progressBar.setVisibility(View.VISIBLE);

        //创建okHttpClient对象
        OkHttpClient mOkHttpClient = new OkHttpClient();


        //创建一个Request
        Request request = new Request.Builder()
                .url(Constants.URLS[tuyype])
                .build();

        //new call
        Call call = mOkHttpClient.newCall(request);

        //请求加入调度
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //请求失败
                Toast.makeText(NappyActivity.this, "加载失败", Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //请求成功

                String result = response.body().string();

                if (!result.equals("") && !result.equals("null")) {

                    //解析JSON数据
                    dataList = ClassifyJson.getClassify(result);
                    if (dataList.size() > 0)
                        handler.sendEmptyMessage(1);
                    else
                        handler.sendEmptyMessage(0);

                } else {
                    //提示用户网络连接失败
                    handler.sendEmptyMessage(0);
                }
            }
        });

    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //取消loading
            progressBar.setVisibility(View.GONE);
            switch (msg.what) {
                case 0://请求解析失败
                    Toast.makeText(NappyActivity.this, "请求失败，稍后再试", Toast.LENGTH_SHORT).show();
                    break;
                case 1://请求解析成功
                    adapter = new ClassifyNappyAdapter(dataList, NappyActivity.this);
                    listView.setAdapter(adapter);

                    //关闭下拉刷新
                    listView.stopRefresh();
                    break;
            }
        }
    };

    /**
     * 点击事件
     */
    private void onItemClickListener() {
        /**
         * 下拉刷新设置
         */
        listView.setXListViewListener(new XListView.IXListViewListener() {
            @Override
            public void onRefresh() {

                //重新开启线程，请求网络数据并解析
                getDateFromWeb();
            }

            @Override
            public void onLoadMore() {

            }
        });
//        radioGroup点击事件
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                Intent it = new Intent();

                switch (i){
                        case R.id.rb_homePager:
                            it.setClass(NappyActivity.this, MainActivity.class);
                            it.putExtra("symbol",1);
                            startActivity(it);

                            break;
                        case R.id.rb_classify:
                            it.setClass(NappyActivity.this, MainActivity.class);
                            it.putExtra("symbol",2);
                            startActivity(it);
                            break;
                        case R.id.rb_shoppingCar:
                            it.setClass(NappyActivity.this, MainActivity.class);
                            it.putExtra("symbol",3);
                            startActivity(it);
                            break;
                        case R.id.rb_personCenter:
                            it.setClass(NappyActivity.this, MainActivity.class);
                            it.putExtra("symbol",4);
                            startActivity(it);
                            break;
                    }

                }

        });

//        搜索
        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(NappyActivity.this, NappyPantsActivity.class);
                startActivity(intent);
            }
        });
//          返回键
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent it = new Intent(NappyActivity.this, NappyPantsActivity.class);
                //携带商品gc_id跳转到下个页面NappyPantsActivity
                it.putExtra("gc_id", dataList.get(i-1).getGc_id());
                startActivity(it);
            }
        });
    }
}
